package com.rw.map.utils;

import java.security.MessageDigest;
import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.MultiValueMap;

/**
 * 签名工具类
 * 
 * @author forest
 *
 */
public class SignUtils {

	private static Logger logger = LoggerFactory.getLogger(SignUtils.class);

	public static String genSign(MultiValueMap<String, String> params, String key) {
		if (params == null || params.size() == 0) {
			return "";
		}
		String[] arrayToSort = params.keySet().toArray(new String[params.size()]);
		Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < arrayToSort.length; i++) {
			if(arrayToSort[i].equals("sign")){
        		continue;
        	}
        	
			sb.append(arrayToSort[i]);
			sb.append("=");
			sb.append(params.get(arrayToSort[i]).get(0));
			sb.append("&");
		}
		sb.append("key=" + key);
		logger.info("签名字符串：{}", sb.toString());
		return genSha1(sb.toString());
	}

	public static String genSha1(String s) {
		MessageDigest md = null;
		String outStr = null;
		try {
			md = MessageDigest.getInstance("SHA-1"); // 选择SHA-1，也可以选择MD5
			byte[] digest = md.digest(s.getBytes("utf-8")); // 返回的是byet[]，要转化为String存储比较方便
			outStr = asHex(digest);
		} catch (Exception nsae) {
			logger.error(nsae.getMessage(), nsae);
		}
		logger.info("签名结果：{}", outStr);
		return outStr;
	}

	/**
	 * 生成时间戳
	 * 
	 * @return
	 */
	public static String getTimeStamp() {
		return String.valueOf(System.currentTimeMillis());
	}
	
	public static void main(String[] args) {
		System.out.println(System.currentTimeMillis());
		System.out.println(System.currentTimeMillis() / 1000);
	}

	/**
	 * 将字节数组转换成16进制字符串
	 * 
	 * @param buf
	 * @return
	 */
	public static String asHex(byte buf[]) {
		StringBuffer strbuf = new StringBuffer(buf.length * 2);
		int i;
		for (i = 0; i < buf.length; i++) {
			if (((int) buf[i] & 0xff) < 0x10)// 小于十前面补零
				strbuf.append("0");
			strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
		}
		return strbuf.toString();
	}

	/**
	 * 使用SHA1算法对字符串进行加密
	 * 
	 * @param str
	 * @return
	 */
	public static String sha1Encrypt(String str) {

		MessageDigest md = null;
		String outStr = null;
		try {
			md = MessageDigest.getInstance("SHA-1"); // 选择SHA-1，也可以选择MD5
			byte[] digest = md.digest(str.getBytes("utf-8")); // 返回的是byet[]，要转化为String存储比较方便
			outStr = asHex(digest);
		} catch (Exception nsae) {
			logger.error(nsae.getMessage(), nsae);
		}
		return outStr;
	}
}
